import 'package:shared_preferences/shared_preferences.dart';

class SPUtils {
  /// 内部构造方法，可避免外部暴露构造函数，进行实例化
  SPUtils._internal();

  static SharedPreferences _spf;

  static Future<SharedPreferences> init() async {
    if (_spf == null) {
      _spf = await SharedPreferences.getInstance();
    }
    return _spf;
  }

  ///主题
  static saveThemeIndex(int value) {
    return _spf.setInt('key_theme_color', value);
  }

  static int getThemeIndex() {
    if (_spf.containsKey('key_theme_color')) {
      return _spf.getInt('key_theme_color');
    }
    return 0;
  }

  ///语言
  static saveLocale(String locale) async {
    return await _spf.setString('key_locale', locale);
  }

  static String getLocale() {
    return _spf.getString('key_locale');
  }

  ///昵称
  static saveNickName(String nickName) async {
    return await _spf.setString('key_nickname', nickName);
  }

  static String getNickName() {
    return _spf.getString('key_nickname');
  }

  ///是否同意隐私协议
  static saveIsAgreePrivacy(bool isAgree) {
    return _spf.setBool('key_agree_privacy', isAgree);
  }

  static bool isAgreePrivacy() {
    if (!_spf.containsKey('key_agree_privacy')) {
      return false;
    }
    return _spf.getBool('key_agree_privacy');
  }

  ///是否已登陆
  static bool isLogined() {
    String nickName = getNickName();
    return nickName != null && nickName.isNotEmpty;
  }

  //角色：teacher or student
  static saveRole(String role) async {
    return await _spf.setString('key_role', role);
  }

  static String getRole() {
    return _spf.getString('key_role');
  }

  //用户名
  static saveUsername(String username) async {
    return await _spf.setString('key_username', username);
  }

  static String getUsername() {
    return _spf.getString('key_username');
  }

  //密码
  static savePassword(String password) async {
    return await _spf.setString('key_password', password);
  }

  static String getPassword() {
    return _spf.getString('key_password');
  }

  //token
  static saveToken(String token) async {
    return await _spf.setString('key_token', token);
  }

  static String getToken() {
    return _spf.getString('key_token');
  }

  //token
  static saveUID(String uid) async {
    return await _spf.setString('key_uid', uid);
  }

  static String getUID() {
    return _spf.getString('key_uid');
  }

  static void clearSession() {
    _spf.remove('key_password');
  }

  //history
  static saveSearchHistory(String username) async {
    return await _spf.setString('key_history', username);
  }

  static String getSearchHistory() {
    String con = _spf.getString('key_history');
    return con;
  }
}
